<!-- <template>
  <Table class="default" filter v-bind="tableOpts" v-on="tableEvent">
    <template #operator>
      <div class="operator-wrap">
        <CommonModify
          :modifyForm="modifyForm"
          ref="CommonModify"
          @submit="onModifySubmit"
        />
      </div>
    </template>
  </Table>
</template>

<script>
import dayjs from "dayjs";
import tableMixins from "@/mixins/tableMixins.vue";
export default {
  name: "InventoryInventoryList",
  mixins: [tableMixins],
  components: {},
  meta: { title: "库存列表", icon: "el-icon-s-home", sort: 5 },
  data() {
    return {
      modifyForm: {
        limit: {
          tag: "el-input-number",
          label: "告警阈值",
          value: "",
          props: {
            min: 0,
            clearable: true,
            placeholder: "请输入告警阈值",
          },
        },
      },
      apiName: "inventoryInventoryList",
      form: {
        materialId: {
          tag: "el-select",
          label: "材料",
          value: "",
          items: [],
          props: {
            clearable: true,
            filterable: true,
          },
        },
        warehouseId: {
          tag: "el-select",
          label: "仓库",
          value: "",
          items: [],
          props: {
            clearable: true,
            filterable: true,
          },
        },
      },
    };
  },
  watch: {},
  mounted() {

    this.$api["materialMaterialList"]({ pageSize: 10000,pageNumber:1 }).then((res) => {
      this.form.materialId.items = res?.rows.map((e) => ({
        label: `${e.materialName} ${e.color} ${e.norm}`,
        value: `${e.materialId || i}`,
      }));
      this.formKey = this.$quinn.guid();
    });
    this.$api["warehouseWarehousePullDownList"]({ pageSize: 10000,pageNumber:1 }).then((res) => {
      this.form.warehouseId.items = res?.map((e) => ({
        label: e.warehouseName,
        value: e.warehouseId,
      }));
      this.formKey = this.$quinn.guid();
    });
  },
  methods: {
    onModifySubmit(e) {
      const { modify, row, form, submitDoneMsg } = e;
      if (modify == "editLimit") {
        form.inventoryId = row.inventoryId;
        this.$api["inventoryInventoryUpdate"](form).then((e) => {
          submitDoneMsg();
          this.fetchCurrentTable();
        });
      }
    },
    showDialog(modify = "add", row = {}) {
      this.dialogVisible = true;
      this.row = row;
      this.modify = modify || "add";
      this.form.warehouseId.items = this.$store.getters.warehouseListItems;
      for (const key in this.form) {
        let defValue = "";
        if (Array.isArray(this.form[key].value)) defValue = [];
        if (Object.hasOwnProperty.call(row, key))
          this.form[key].value = row[key];
        else this.form[key].value = defValue;
      }
      this.formKey = this.$quinn.guid();
    },
    formatData(res) {
      this.total = res?.count || res?.total || 0;
      this.dataSource = (res?.rows || res?.data || res || []).map((e) => {
        if (e.updatedAt)
          e.updatedTime = dayjs(e.updatedAt).format("YYYY-MM-DD HH:mm:ss");
        if (e.createdAt) {
          e.createdTime = dayjs(e.createdAt).format("YYYY-MM-DD HH:mm:ss");
        }
        e.warehouseName = e?.warehouse?.warehouseName;
        return {
          ...e.material,
          ...e,
        };
      });
    },
    handleAction(opts, row) {
      const { supplierName: name, supplierId } = row;
      if (["edit"].includes(opts)) this.showDialog(opts, row);
      else if (opts == "editLimit") {
        this.setModifyValue(row);
        const ref = this.$refs["CommonModify"];
        ref && ref.showDialog(opts, row);
      } else if (opts === "delete")
        this.showConfirm(`确认删除【${name}】？`, "supplierSupplierDelete", {
          supplierId,
        });
      else {
        const ref = this.$refs[opts];
        ref && ref.showDialog(opts, row);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.default /deep/ .el-button--primary {
  border-color: #ff6a00;
  background-color: #ff6a00;
}

.default /deep/ .el-button:hover {
  color: white;
  border-color: #f59a59;
  background-color: #f59a59;
}
.default /deep/ .el-button:active{
  color: white;
  border-color: #f59a59;
  background-color: #f59a59;
}
.default /deep/ .el-button:focus{
  color: #ff6a00;
  border-color: #fdf2e9;
  background-color:#fdf2e9;
}

/deep/ .el-input__inner:hover{
  border-color: #ff6a00 !important;
}
/deep/ .el-input__inner:focus{
  border-color: #ff6a00 !important;
}
/deep/ .selected{
  color:#ff6a00 !important;
}
/deep/ .active{
  color:#ff6a00 !important;
}
/deep/ .selected{
  color:#ff6a00 !important;
}
/deep/ .el-loading-text{
  color:#ff6a00 !important;
}
/deep/ .el-icon-loading{
  color:#ff6a00 !important;
}
</style> -->


<template>
  <el-card class="default">
    <div class="flex" style="margin-bottom: 20px;justify-content: space-between;">
      <div class="flex">
        <div class="flex" style="align-items: center;">
          <div style="width:120px;text-align: center;">材料名称:</div>
          <el-input v-model="materialName" @keyup.enter.native="getMaterial" size="small" palceholder="请输入材料名称"
            clearable></el-input>
        </div>
        <div class="flex" style="align-items: center;">
          <div style="width:120px;text-align: center;">仓库:</div>
          <el-select @change="getMaterial" v-model="warehouseId" clearable size='small' style="width:100%"
            placeholder="请选择">
            <el-option v-for="item in warehouseList" :key="item.warehouseId" :label="item.warehouseName"
              :value="item.warehouseId">
            </el-option>
          </el-select>
        </div>
      </div>
      <div>
        <el-button type="primary" @click="saveList">导出</el-button>
      </div>
    </div>
    <div>
      <el-table :data="list" element-loading-text="拼命加载中" border element-loading-spinner="el-icon-loading"
        v-loading="loading" style="width: 100%;"
        :headerCellStyle="{ 'textAlign': 'center', 'fontWeight': '400', 'background': '#ff6a00', 'color': 'white' }"
        :cellStyle="{ 'textAlign': 'center', 'fontSize': '12px' }" :height="maxHeight">
        <el-table-column type="expand" label="展开" width="50px">
          <template slot-scope="props">
            <el-table class="table" :data="props.row.material" stripe style="width: 100%" show-summary border
              :headerCellStyle="{ 'textAlign': 'center', 'fontWeight': '400', }"
              :cellStyle="{ 'textAlign': 'center', 'fontSize': '12px' }">
              <el-table-column prop="material.materialId" label="编码" min-width="100">
              </el-table-column>
              <el-table-column prop="material.materialName" label="名称" min-width="280">
              </el-table-column>
              <el-table-column prop="material.norm" label="规格" min-width="100">
              </el-table-column>
              <el-table-column prop="material.color" label="颜色" min-width="100">
              </el-table-column>
              <el-table-column prop="material.unit" label="单位" min-width="100">
              </el-table-column>
              <el-table-column prop="count" label="库存" min-width="100">
              </el-table-column>
              <el-table-column prop="outCount" label="出库" min-width="100">
              </el-table-column>

              <!-- <el-table-column label="出库">
                <template slot-scope="scope" >
                  {{Number(scope.row.inCount - scope.row.count)}}
                </template>
</el-table-column> -->
              <el-table-column prop="inCount" label="入库" min-width="100">
              </el-table-column>
              <el-table-column prop="checkCount" label="盘点" min-width="100">
              </el-table-column>
              <el-table-column prop="changeCount" label="变更" min-width="100">
              </el-table-column>
              <el-table-column prop="damageCount" label="损坏" min-width="100">
              </el-table-column>
              <el-table-column prop="warehouse.warehouseName" label="仓库" min-width="100">
              </el-table-column>
              <el-table-column label="状态" min-width="100">
                <template slot-scope="scope">
                  <div v-if="scope.row.warehouseId == 1 || scope.row.warehouseId == 10">
                    <el-link v-if="(scope.row.count / scope.row.material.storeAverageUseCount) < 50"
                      type="danger">预警</el-link>
                    <el-link v-else>正常</el-link>
                  </div>
                  <div v-else>
                    <el-link v-if="(scope.row.count / scope.row.material.storeAverageUseCount) < 30"
                      type="danger">预警</el-link>
                    <el-link v-else>正常</el-link>
                  </div>
                </template>
              </el-table-column>
              <!-- <el-table-column label="操作" fixed='right' min-width="180px">
                <template slot-scope="scope">
                  <el-button size="small" @click="edifMaterail('update', scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click='deleteMaterail(scope.row)'>删除</el-button>
                </template>
              </el-table-column> -->
            </el-table>
          </template>
        </el-table-column>
        <el-table-column label="分类ID" prop="cateId" min-width="200px"></el-table-column>
        <el-table-column label="分类名称" prop="name" min-width="200px"></el-table-column>
        <el-table-column label="总库存" prop="allCount" min-width="200px"></el-table-column>
        <el-table-column label="可用店铺数量" prop="inventoryStoreCount" min-width="200px"></el-table-column>
        <el-table-column label="库存状态" min-width="100">
          <template slot-scope="scope">
            <div v-if="warehouseId == 1 || warehouseId == 10">
              <el-link v-if="scope.row.inventoryStoreCount < 50" type="danger">预警</el-link>
              <el-link v-else>正常</el-link>
            </div>
            <div v-else>
              <el-link v-if="scope.row.inventoryStoreCount < 30" type="danger">预警</el-link>
              <el-link v-else>正常</el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

  </el-card>

</template>
<script>
import Decimal from 'decimal.js';
import * as XLSX from 'xlsx';
export default {
  name: "InventoryInventoryList",
  components: {},
  meta: { title: "库存列表", icon: "el-icon-s-home", sort: 20, authority: 113 },
  data() {
    return {
      list: [],
      maxHeight:0,
      saveData: [],
      warehouseList: [],
      warehouseId: '',
      materialName: '',
      loading: false,
    }
  },
  mounted() {
    this.getWarehouseList();
    this.$nextTick(() => {
      this.maxHeight = window.innerHeight - 240;
    })
  },
  methods: {
    getWarehouseList() {
      this.$api.warehouseWarehousePullDownList({ pageNumber: 1, pageSize: 100000 }).then(async res => {
        this.warehouseList = res;
        this.warehouseId = this.warehouseList[0].warehouseId;
        await this.getMaterial();
      })
    },
    saveList() {
      if(this.loading) {
        this.$message.error("请等页面加载完成后再导出!");
        return;
      };
      if(this.saveData.length < 1) {
        this.$message.error("当前材料无库存!");
        return;
      };
      const wb = XLSX.utils.book_new();
      let data = [['商品名称', '商品编码', '库存','色号']]
      this.saveData.map(el => {
        data.push([el.name, el.materialId, el.count,el.material.color])

      })
      const ws = XLSX.utils.aoa_to_sheet(data);
      // 将工作表添加到工作簿
      XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

      // 导出工作簿为 Blob 对象
      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });

      // 创建一个 Blob 对象
      const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });

      // 使用 Blob 对象创建一个链接
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      let warehouseName = ''
      if(this.warehouseId == 1 )  warehouseName = '宁乡仓';
      if(this.warehouseId == 2 )  warehouseName = '广东仓';
      if(this.warehouseId == 4 )  warehouseName = '广西仓';
      if(this.warehouseId == 5 )  warehouseName = '云南仓';
      if(this.warehouseId == 7 )  warehouseName = '河南仓';
      if(this.warehouseId == 10 )  warehouseName = '重庆仓';
      if(this.warehouseId == 11 )  warehouseName = '贵州仓';

      link.download = `${warehouseName}-${new Date().getTime()}.xlsx`;

      // 触发下载
      link.click();

      // 清理
      URL.revokeObjectURL(link.href);
      function s2ab(s) {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
      }
    },
    getMaterial() {
      this.loading = true
      this.$api.inventoryInventoryList({ pageSize: 1000000, pageNumber: 1, materialName: this.materialName, warehouseId: this.warehouseId }).then(res => {
        this.saveData = res.rows;
        let arr = [];
        res.rows.map(el => {
        //  el.damageCount = el.damageCount ? el.damageCount : 0
        //  el.outCount = (el.inCount + el.checkCount+el.changeCount) - (el.damageCount + el.count);
          if (!arr.includes(el.classificationId)) {
            arr = arr.concat([el.classificationId])
          }
        })
        let categroy = [];
        arr.map(el => {
          categroy = categroy.concat({ 'cateId': el, 'material': [] })
        })
        res.rows.map(el => {
          categroy.map(k => {
            if (el.classificationId === k.cateId) {
              k.name = el.name;
              k.material.push(el)
            }
          })
        })

        this.list = categroy;
        this.list.map(el => {
          el.inventoryStoreCount = new Decimal(0);
          el.allCount = 0;

          el.material.map(k => {
            el.allCount += k.count;
            el.inventoryStoreCount = Decimal(el.inventoryStoreCount).plus(Decimal(k.count).div(Decimal(k.material.storeAverageUseCount)).toFixed(0)).toNumber();
          })

        })
        this.loading = false;
      })

    }
  },
}


</script>
<style lang="less" scoped>
.table /deep/ .el-table__footer-wrapper .el-table__footer .el-table__cell {
  text-align: center;
  font-size: 12px;
  font-weight: 400;
  color: #ff6a00;
}

.default /deep/ .el-button {
  border-color: #ff6a00;
  background-color: #ff6a00;
}

.default /deep/ .el-button:hover {
  color: white;
  border-color: #f59a59;
  background-color: #f59a59;
}

/deep/ .el-button:hover {
  color: black;
  border-color: #DCDFE6;
  background-color: white;
}

span /deep/ .el-button:nth-child(2) {
  border-color: #ff6a00;
  background-color: #ff6a00;
}

span /deep/ .el-button:nth-child(2):hover {
  color: white;
  border-color: #f59a59;
  background-color: #f59a59;
}

/deep/ .el-input__inner:hover {
  border-color: #ff6a00 !important;
}

/deep/ .el-input__inner:focus {
  border-color: #ff6a00 !important;
}

/deep/ .selected {
  color: #ff6a00 !important;
}

/deep/ .active {
  color: #ff6a00 !important;
}

/deep/ .selected {
  color: #ff6a00 !important;
}

/deep/ .el-loading-text {
  color: #ff6a00 !important;
}

/deep/ .el-icon-loading {
  color: #ff6a00 !important;
}
</style>
